jQuery.support.cors = true;
/**
 * 扩展jquery的事件注册，可以为选择器子选择器注册多个事件 
 * 	$("#talkfield").onEvent({
 *		'click' : {
 *   		'.page a' : function(){
 *    			var url = $(this).attr('url'); 
 *    		},
 *    		'tbody tr' : function(){
 * 				var bSelected = $(this).hasClass("row_selected");
 * 			} 
 * 		} 
 * 	});
 */
$.fn.onEvent = function(obj) {
	for ( var event in obj)
		for ( var selector in obj[event])
			$(this).on(event, selector, obj[event][selector]);
	return this;
};

//对Date的扩展，将 Date 转化为指定格式的String 
//月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
//年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
//例子： 
//(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
//(new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function(fmt) { //author: meizz 
	var o = { 
		"M+" : this.getMonth()+1,                 //月份 
		"d+" : this.getDate(),                    //日 
		"h+" : this.getHours(),                   //小时 
		"m+" : this.getMinutes(),                 //分 
		"s+" : this.getSeconds(),                 //秒 
		"q+" : Math.floor((this.getMonth()+3)/3), //季度 
		"S"  : this.getMilliseconds()             //毫秒 
	}; 
	if(/(y+)/.test(fmt)) {
		fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
	}
	for(var k in o) {
		if(new RegExp("("+ k +")").test(fmt)){
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); 
		}
	}
	return fmt; 
};
/**
 * 
 * @param option 初始化参数，对象形式
 * @param icon 图标参数，warning、info、question、correct、incorrect五个字符串之一，默认为info
 */
function MessageBox(option, icon){
	var settings = {
		height : 240,
		dialogClass: 'message-dialog green-dialog no-close',
		autoOpen: true,
		modal: true,
		resizable: false,
		title : '提示',
		content : '在参数中添加content属性以显示内容',
		close: function( event, ui ) {
			$(this).dialog('destroy').remove();
		},
		buttons : [{
			text : '我知道了',
			click : function(){
				$( this ).dialog( 'close' );
			}
		}]
	};
	$.extend(settings, option);
	$('.TinSoMessageBox_Content').remove();
	$('<div class="TinSoMessageBox_Content">' + settings.content + '</div>').css({
		'position' : 'fixed',
		'left' : '-10000px',
		'top' : '0px',
		'font-family' : '"Hiragino Sans GB", "Lantinghei SC", "Microsoft Yahei",SimSun',
		'font-size' : '18px'
	}).appendTo('body');
	var textHeight = $('.TinSoMessageBox_Content').height(); 
	var textWidth = $('.TinSoMessageBox_Content').width();
	$('.TinSoMessageBox_Content').remove();
	
	settings.width = textWidth + 180;
	if(settings.width < 400){
		settings.width = 400;
	}else if(settings.width > 700){
		settings.width = 650;
	}
	if(textHeight < 48){
		textHeight = 48;
	}
	settings.height = textHeight + 160;
	if(settings.height < 240){
		settings.height = 240;
	}
	if($('#TinSoMessageBox').length != 0){
		$('#TinSoMessageBox').remove();
	}
	if(icon == undefined){
		icon = 'info';
	}
	var div = '<div id="TinSoMessageBox">';
	div += '<div class="dib-wrap messageContent">';
	div += '<div class="dib dialog-icon ' + icon + '"></div>';
	div += '<div class="dib message-info">' + settings.content + '</div>';
	div += '</div></div>';
	$(div).appendTo('body');
	$('#TinSoMessageBox').dialog(settings);
	$('.message-dialog #TinSoMessageBox').height(textHeight);
	
	if(settings.width > 400){
		$('.message-dialog .messageContent .message-info').width(settings.width - 170);
	}
	
	if(settings.height > 240){
		$('.message-dialog .messageContent .message-info').height(textHeight);
	}else{
		var height = ($('.message-dialog #TinSoMessageBox').height() - $('.message-dialog .messageContent').height()) / 2;
		$('.message-dialog .messageContent').css('margin-top', height);
	}
	$('.message-dialog .messageContent').css('margin-top', '0px');
	$('#TinSoMessageBox').css('height', 'auto');
}
/**
 * 资源加载加载等待对话框
 * @param content 初始化参数，或'close'关闭对话框
 */
function ResourceLoadingMessageBox(content){
	var settings = {
		dialogClass: 'loading-message-dialog green-dialog',
		width: 360,
		height: 240,
		autoOpen: true,
		modal: true,
		resizable: false,
		content : '资源加载中',
		close: function( event, ui ) {
			$(this).dialog('destroy').remove();
		}
	};
	
	if(content == 'close'){
		if($('#TinSoLoadMessageBox').length > 0){
			ResourceLoadingMessageBox.loadingTime = new Date().getTime() - ResourceLoadingMessageBox.loadingTime - 1000;
			if(ResourceLoadingMessageBox.loadingTime < 0 && typeof(_DEBUG) == 'undefined'){
				ResourceLoadingMessageBox.loadingTime = 0 - ResourceLoadingMessageBox.loadingTime;
			}else{
				ResourceLoadingMessageBox.loadingTime = 0;
			}
			$('#TinSoLoadMessageBox').delay(ResourceLoadingMessageBox.loadingTime).dialog('close');
		}
		return;
	}else if(content != undefined){
		settings.content = content;
	}
	ResourceLoadingMessageBox.loadingTime = new Date().getTime();
	if($('#TinSoLoadMessageBox').length != 0){
		$('#TinSoLoadMessageBox .message-info').html(settings.content);
		return;
	}
	var div = '<div id="TinSoLoadMessageBox">';
	div += '<div class="dib-wrap messageContent">';
	div += '<div class="dib dialog-icon"></div>';
	div += '<div class="dib message-info">' + settings.content + '</div>';
	div += '</div></div>';
	$(div).appendTo('body');
	$('#TinSoLoadMessageBox').dialog(settings);
	var height = ($('.loading-message-dialog #TinSoLoadMessageBox').height() - $('.loading-message-dialog #TinSoLoadMessageBox .messageContent').height()) / 2 - 10;
	$('.loading-message-dialog #TinSoLoadMessageBox .messageContent').css('margin-top', height);
}
ResourceLoadingMessageBox.loadingTime = 0;


/**
 * 加载等待对话框
 * @param content 初始化参数，或'close'关闭对话框
 */
function LoadingMessageBox(content){
	var settings = {
		dialogClass: 'loading-message-dialog green-dialog',
		width: 360,
		height: 240,
		autoOpen: true,
		modal: true,
		resizable: false,
		content : '正在加载',
		close: function( event, ui ) {
			$(this).dialog('destroy').remove();
		}
	};

	if(content == 'close'){
		if($('#TinSoLoadMessageBox').length > 0){
			LoadingMessageBox.loadingTime = new Date().getTime() - LoadingMessageBox.loadingTime - 1000;
			if(LoadingMessageBox.loadingTime < 0 && typeof(_DEBUG) == 'undefined'){
				LoadingMessageBox.loadingTime = 0 - LoadingMessageBox.loadingTime;
			}else{
				LoadingMessageBox.loadingTime = 0;
			}
			$('#TinSoLoadMessageBox').delay(LoadingMessageBox.loadingTime).dialog('close');
		}
		return;
	}else if(content != undefined){
		settings.content = content;
	}
	LoadingMessageBox.loadingTime = new Date().getTime();
	if($('#TinSoLoadMessageBox').length != 0){
		$('#TinSoLoadMessageBox').remove();
	}
	var div = '<div id="TinSoLoadMessageBox">';
	div += '<div class="dib-wrap messageContent">';
	div += '<div class="dib dialog-icon"></div>';
	div += '<div class="dib message-info">' + settings.content + '</div>';
	div += '</div></div>';
	$(div).appendTo('body');
	$('#TinSoLoadMessageBox').dialog(settings);
	var height = ($('.loading-message-dialog #TinSoLoadMessageBox').height() - $('.loading-message-dialog #TinSoLoadMessageBox .messageContent').height()) / 2 - 10;
	$('.loading-message-dialog #TinSoLoadMessageBox .messageContent').css('margin-top', height);
}
LoadingMessageBox.loadingTime = 0;

/**
 * 解析Url中的锚点参数
 * @returns {Object} 参数对象
 */
function parseUrlAnchor(){
	var params = new Object();
	var url = window.location.hash;
	var paramSep = '';
	if($.browser.msie && $.browser.version < 9){
		paramSep = '#';
	}else{
		paramSep = '?';
	}
	var pos = url.indexOf(paramSep);
	if(pos != -1){
		var anchorParam = url.substring(1);
		var strs = anchorParam.split('&');
		for(var i = 0; i < strs.length; i++){
			var param = strs[i].split('=');
			param[1] = decodeURIComponent(param[1]);
			if(param[1].search(',') != -1){
				param[1] = param[1].split(',');
			}
			params[param[0]] = param[1];
		}
	}
	return params;
}
/**
 * 解析Url中的查询参数
 * @returns {Object} 参数对象
 */
function parseUrlQuery(url){
	var params = new Object();
	if(!url){
		url = window.location.href;
	}
	url = url.replace(/&_suid=[^&]*/, '');
	var pos = url.indexOf('?');
	if(pos != -1){
		var anchorParam = url.substring(pos + 1);
		var strs = anchorParam.split('&');
		for(var i = 0; i < strs.length; i++){
			var param = strs[i].split('=');
			param[1] = decodeURIComponent(param[1]);
			if(param[1].search(',') != -1){
				param[1] = param[1].split(',');
			}
			params[param[0]] = param[1];
		}
	}
	return params;
}
/**
 * 替换Url中的查询参数
 * @param url string 地址
 * @param name string 参数名
 * @param value string 参数值
 * @returns string 
 */
function replaceUrlQuery(url, name, value){
	if(!url){
		url = window.location.href;
	}
	if(value instanceof Array){
		value = value.join(',');
	}
	url = url.replace(/&_suid=[^&]*/, '');
	var pos = 0;
	if($.browser.msie && $.browser.version < 9){
		pos = url.search(/#?\?/);
	}else{
		pos = url.search(/\?/);
	}
	var newUrl = '';
	if(pos != -1){
		newUrl = url.substring(0, pos) + '?';
		var anchorParam = url.replace(/[^\?]*\?([^\?]*)/, '$1');
		var strs = anchorParam.split('&');
		var bNotFound = true;
		for(var i = 0; i < strs.length; i++){
			var param = strs[i].split('=');
			param[1] = decodeURIComponent(param[1]);
			if(param[0] == name){
				param[1] = value;
				bNotFound = false;
			}
			if(param[1] !== null){
				if(i != 0){
					newUrl += '&';
				}
				newUrl += param[0] + '=' + param[1];
			}
		}
		if(bNotFound && value !== null){
			newUrl += '&' + name + '=' + value;
		}
	}else{
		if(value !== null){
			newUrl = url + '?' + name + '=' + value;
		}
	}
	return newUrl;
}
/**
 * 窗口大小改变时，重置body的宽度，否则某些div的背景将不能填满整个页面
 */
function resizeBodyWidth(){
	var width = $(window).width();
	if(width < 980){
		width = 980;
	}
	$('body, .top_nav_content').width(width);
}
$(function(){
	//如果已登录，显示姓名
	var userId = $.cookie('TsUserId');
	var payStatus = $.cookie('PayStatus');
	if (userId != undefined) {
		var name = $.cookie("TsName");
		if(window.location.origin == TinSoConfig.teacher){
			name += ' 老师';
		}
		name += '，欢迎您！';
		$('.user_info .uname').html(name);
		$('.user_info').show();
	}else{
		$('.register').show();
		$('.login').show();
	}
	$(window).resize(resizeBodyWidth);
	resizeBodyWidth();
	$('body').onEvent({
		'click' : {
			//退出登录
			'.logout' : function() {
				$.post(TinSoConfig.host + '/User/logout.html', function(data){
					if (data) {
						//刷新页面
						if (data.isExaminer) {
							window.location.replace(TinSoConfig.teacher);
						} else {
							window.location.replace(TinSoConfig.www);
						}
					}
				});
			},
			'.login' : function(){
				$('.loginDialog').dialog({
					dialogClass: 'login-dialog green-dialog',
					height : 300,
					width : 370,
					autoOpen: true,
					modal: true,
					resizable: false,
					beforeClose : function(){
						$('.loginDialog .password').val('');
					}
				});
			},
			'.member_login' : function(){
				var username = $(".loginDialog .login_username").val();
				if (username == undefined || username == "") {
					$('.msg').html('用户名不能为空');
					return;
				}
				var password = $('.loginDialog .login_password').val();
				if (password == undefined || password == "") {
					$('.msg').html('密码不能为空');
					return;
				}
				var param = {
					username : username,
					password : $.md5(password)
				};
				$.ajax({
					url : TinSoConfig.host + '/User/login.html',
					data : param,
					type : 'POST',
					global : false,
					success : function(data){
						if (data.status) {
							if(window.location.pathname == '/User/register.html'){
								window.location.replace(TinSoConfig.www);
								return;
							}
							$('.loginDialog').dialog('close');
							$('li.user_info').show();
							$('li.user_center').show();
							$('.register').hide();
							$('.login').hide();

							var userId = $.cookie('TsUserId');
							var name = $.cookie("TsName");
							if(window.location.origin == TinSoConfig.teacher){
								$('.sidebar .user_name_title .user_name_title').remove();
								var html = '<div class="user_name_title">' + name + '</div><div class="user_name_title">教师码:' + userId + '</div>';
								$('.sidebar .user_name_title').html(html);
								name += ' 老师，欢迎您！';
							}else if(window.location.origin == TinSoConfig.student){
								name += ' 同学，欢迎你！';
							}
							$('.user_info .uname').text(name);
						} else {
							$('.loginDialog .msg').html('用户名或密码不正确');
						}
					}
				});
			}
		}
	});
	$('.top_nav_content').css('left', 0 - $(window).scrollLeft());
	$(window).scroll(function(e){
		$('.top_nav_content').css('left', 0 - $(window).scrollLeft());
	});

	$(document).tooltip({
		items	: '.footer_link.wenxin',
		content	: function(){
			return '<img class="map" alt="听说科技" src="' + TinSoConfig.pub + '/images/qr/weixin.png"/>';
		}
	});
	
	//边栏注册事件，并添加滚动条
	$('.sidebar, .sidebar2, .edit_homework, .preview_sidebar').onEvent({
		'click' : {
			'.pull_down' : function(e){
				// 
				$(this).closest('.sidebar_cnt_ul').find('a.current').removeClass('current');
				$(this).children('a').addClass('current');
				// 如果是不可折叠的，则返回
				if($(this).hasClass('noncollapsible')){
					return;
				}
				e.stopPropagation();
				if($(this).hasClass('active')){
					$(this).removeClass('active');
				}else {
					$(this).addClass('active').siblings('.pull_down').removeClass('active');
				}
			}/*,
			'a.item' : function(e){
				e.stopPropagation();
				if(!$(this).hasClass('current')){
					$(this).closest('.sidebar_cnt_ul').find('a.current').removeClass('current');
					$(this).addClass('current');
				}
			}*/
		}
	});
	$('.sidebar, .sidebar2, .preview_sidebar').mCustomScrollbar({
		//scrollButtons:{enable:true},
		theme: 'thick'
	});
	// 没有权限或session过期时
	$(document).ajaxSuccess(function(event, request, settings){
		if(request.responseText == ''){
			return;
		} 
		// 数据
		var data = null;
		// 调用者是否是ajaxfileupload.js文件
		if(settings.func_source == 'ajaxfileupload'){
			data = eval( "data = " + $(request.responseText).html());
		}else{
			if(request.responseText!=undefined){
				data = JSON.parse(request.responseText);
			}else{
				return;
			}
		}
		if(typeof(data) == 'undefined'){
			return;
		}
		if(typeof(data.status) == 'undefined'){
			return;
		}
		var options = {
			buttons : [{
				text : '我知道了',
				click : function(){
					$( this ).dialog( 'close' );
					if(/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/.test(data.url)){
						window.location.href = data.url;
					}
				}
			}]
		};
//		LoadingMessageBox('close');
		if(data.status === 0){
			if(data.info == '服务器的代码出现问题了，快鞭策攻城狮修改'){
				var content = '';
				if(typeof(_DEBUG) == 'undefined'){
					options.content = '服务器出错了!';
				}else{
					options.aspectRatio = settings.url.length / 16;
					options.title = '服务器代码出错，请求地址如下';
					options.width = 600;
					options.content = '<span style="word-break:break-word;text-align:left;">' + settings.url + '</span>';
				}
				MessageBox(options, 'incorrect');
				$('.messageContent .message-info').css('width', 'auto');
				$('.messageContent .dialog-icon').remove();
			}else if(data.url != ''){
				options.content = data.info;
				MessageBox(options, 'incorrect');
			}
			console.log(data.info + settings.url);
		}else if(data.status === 1 && data.url != '' && typeof data.info=='string' && data.info != ''){
			options.content = data.info;
			MessageBox(options, 'info');
		}
	});
	// ajax出错时的处理
	$(document).ajaxError(function(event, request, settings){
		if(request.readyState == 0)
		{
			return;
		}
		LoadingMessageBox('close');
		var settings = {
			content : '网络异常或者连接中断！',
			buttons : [{
				text : '我知道了',
				click : function(){
					$( this ).dialog( 'close' );
				}
			}]
		};
		if ($.browser.msie && (request.statusText == "No Transport" || request.statusText == "Error: 拒绝访问。\r\n") ){
			settings.content += 'IE浏览器没有开启跨域支持，请点击浏览器的的“工具->Internet 选项->安全->自定义级别”将“其他”选项中的“通过域访问数据源”选中为“启用”或者“提示”，然后点击确定。';
		}
		MessageBox(settings, 'incorrect');
	});
	// 教师、学生做单点登录检测
	if(TinSoConfig.host == TinSoConfig.teacher || TinSoConfig.host == TinSoConfig.student){
		var msgHandle = setInterval(function(){
			var userId = $.cookie('TsUserId');
			if(!userId || userId == 1){
				return;
			}
			$.post(TinSoConfig.host + '/Message/lists.html', function(data){
				// 获取到数据
				if(!!data.status){
					var info = data.info;
					// 单点登录检测没通过
					if(!info.login){
						var content = '账号已在其他设备登录，如非本人操作，则密码可能已泄露，请登录并前往<a class="profile_url">个人中心</a>修改密码。';
						content += '如已不能登录，请联系客服QQ:400-9999-622。';
						var settings = {
							content : content,
							buttons : [{
								text : '我知道了',
								click : function(){
									window.location.href = TinSoConfig.www;
									$( this ).dialog( 'close' );
								}
							}]
						};
						MessageBox(settings, 'warning');
						$('.profile_url').attr('href', TinSoConfig.host + '/User/profile.html');
						clearInterval(msgHandle);
						return;
					}
					// 教师
					if(TinSoConfig.host == TinSoConfig.teacher){
					}
					// 学生
					else if(TinSoConfig.host == TinSoConfig.student){
					}
				}
			});
		}, 60000);
	}
	// 禁止后退操作
	if (!!window.history && !!window.history.pushState) {
		history.pushState(null, null, document.URL);
		window.addEventListener('popstate', function () {
			history.pushState(null, null, document.URL);
		});
	}
});

//导航高亮
function highlightNav(url){
    $('.select_nav').find('a[href="'+url+'"]').addClass('current');
}

function brosweWarning(){
	if($('.browser_warning_dialog').length == 0){
		var dialog = '<div class="browser_warning_dialog"><div class="waring_cnt">您正在使用的IE浏览器版本过低，网站的某些功能可能会受到影响，建议您安装Chrome(谷歌)、FireFox(火狐)、Opera、360、猎豹等浏览器。</div></div>';
		$('body').append(dialog);
	}
	$('.browser_warning_dialog').dialog({
		width : 400,
		height : 300,
		dialogClass: 'large-dialog green-dialog',
		modal : true,
		resizable : false,
		buttons: {
			'我知道了': function(){
				$(this).dialog('close');
			}
		}
	});
}

function isAndroid(){
	if(navigator.userAgent.search('Android') != -1){
		return true;
	}
	return false;
}
function isIOS(){
	if(navigator.userAgent.search('iP') != -1){
		return true;
	}
	return false;
}

// 提示
function tip(message){
	var time = new Date();
	var id = time.getTime(); //时间戳定义tip的id
	var tip = '<div id="'+id+'" class="msg_tips">'+message+'<span class="close_tip"></span></div>';
	$('.msg_tips_list').append(tip); //追加tip
	// 3秒显示，2秒淡出
	setTimeout(function(){
		$('#'+id).fadeOut(2000);
	},3000);
	// 淡出后删除tip
	setTimeout(function(){
		$('#'+id).remove();
	},5000);
	// 点击x直接删除tip
	$('.close_tip').click(function(){
		$(this).parent('.msg_tips').remove();
	});
}

/**
 * 验证密码
 * @param  {[type]} password         [description]
 * @param  {[type]} confirm_password [description]
 * @return {[type]}                  [description]
 */
function verifyPassword(password, confirm_password) {
	// 返回的验证结果
	var res = {status: true, msg: ''};

	if (password == '') {
		res.status = false;
		res.msg = '请先填写新密码';
		return res;
	}

	if (confirm_password == '') {
		res.status = false;
		res.msg = '请先填写确认密码';
		return res;
	}

	if (password.length < 6 || password.length > 20) {
		res.status = false;
		res.msg = '密码长度必须为 6~20 位';
		return res;
	}

	// var regex = new RegExp('^(((?=.*[0-9])(?=.*[a-zA-Z])|(?=.*[0-9])(?=.*[^\s0-9a-zA-Z])|(?=.*[a-zA-Z])(?=.*[^\s0-9a-zA-Z]))[^\s]+)$');
	var regex = new RegExp('^(?!^[0-9]+$)(?!^[a-zA-Z]+$)(?!^[~!@_#$%^&*]+$)[a-zA-Z0-9~!@_#$%^&*]+$');
	if (!regex.test(password)) {
		res.status = false;
		res.msg = '密码必须包含(字母、数字、特殊字符)中的两种';
		return res;
	}

	if (password !== confirm_password) {
		res.status = false;
		res.msg = '密码和确认密码不一致';
		return res;
	}

	return res;
}